package com.thingcom.delinrobot.utils;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import com.thingcom.delinrobot.R;

import java.util.Objects;

import static com.thingcom.delinrobot.Common.Constant.USER_ALIS;


public class ChangeNameDialog extends DialogFragment {
    private OnChangeNameListener listener;
    private EditText etName;
    private String alis;
    public static ChangeNameDialog newInstance(String alis) {
        Bundle args = new Bundle();
        args.putString(USER_ALIS,alis);
        ChangeNameDialog changeNameDialog = new ChangeNameDialog();
        changeNameDialog.setArguments(args);
        return  changeNameDialog;
    }

    public void setOnChangeNameListener(OnChangeNameListener listener){
        this.listener = listener;
    }

    public interface OnChangeNameListener {
        void onFinish(String name);
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle!=null){
            alis = bundle.getString(USER_ALIS);
            MyLog.i("设备名字", "onCreate: "+"alias"+alis);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Objects.requireNonNull(getDialog()).requestWindowFeature(Window.FEATURE_NO_TITLE);
        Objects.requireNonNull(getDialog().getWindow()).setBackgroundDrawableResource(android.R.color.transparent);
        View view = inflater.inflate(R.layout.change_device_name_layout,container,false);
        etName = view.findViewById(R.id.et_change_name);
        if (alis!=null){
            etName.setText(alis);
        }
        Button buttonOk = view.findViewById(R.id.dialog_confirm);
        buttonOk.setOnClickListener(v -> {
            if (TextUtils.isEmpty(etName.getText().toString())){
                ToastUtil.showToast(getContext(),"The device name cannot be empty");
                return;
            }
            String name = etName.getText().toString();
            if (listener != null){
                listener.onFinish(name);
                dismiss();
            }


        });

        Button buttonConcel = view.findViewById(R.id.dialog_cancel);

        buttonConcel.setOnClickListener(v -> dismiss());

        return view;
    }

}
